package fm.dongman.animefm.view.adapter

import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup

/**
 * 实用 RecyclerView 的适配器
 * 第一泛型：数据的类型 T
 * 第二泛型：ViewHolder VH
 * Created by shize on 2017/11/21.
 */
abstract class UsedAdapter<VH : UsedAdapter.UsedViewHolder> : RecyclerView.Adapter<UsedAdapter.UsedViewHolder>() {
    private var mHeaderView: View? = null // 头部 View
    private var mFooterView: View? = null // 底部 View

    override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): UsedViewHolder {
        return when (viewType) {
            TYPE_HEADER -> UsedViewHolder(mHeaderView!!)
            TYPE_FOOTER -> UsedViewHolder(mFooterView!!)
            else -> onCreateVH()
        }
    }

    /**
     * 创建普通的 UsedViewHolder
     */
    abstract fun onCreateVH(): VH

    @Suppress("UNCHECKED_CAST")
    override fun onBindViewHolder(holder: UsedViewHolder, position: Int) {
        var pos = position
        if (mHeaderView != null) {
            --pos
        }
        if (getItemViewType(position) == TYPE_NORMAL) onBindVH(holder as VH, pos)
    }

    /**
     * 绑定 ViewHolder
     */
    abstract fun onBindVH(holder: VH, position: Int)

    override fun getItemCount(): Int {
        var count = getDataTotal()
        if (mHeaderView != null) {
            ++count
        }
        if (mFooterView != null) {
            ++count
        }
        return count
    }

    /**
     * 获取 item 总数
     */
    abstract fun getDataTotal(): Int

    override fun getItemViewType(position: Int): Int {
        if (mHeaderView != null && position == 0) {
            return TYPE_HEADER
        }
        if (mFooterView != null && position == itemCount - 1) {
            return TYPE_FOOTER
        }
        return TYPE_NORMAL
    }

    /**
     * 添加头部 View
     */
    fun addHeaderView(headerView: View) {
        mHeaderView = headerView
    }

    /**
     * 添加底部 View
     */
    fun addFooterView(footerView: View) {
        mFooterView = footerView
    }

    /**
     * 移除底部
     */
    fun removeFooterView() {
        mFooterView = null
        notifyDataSetChanged()
    }

    /**
     * 移除头部
     */
    fun removeHeaderView() {
        mHeaderView = null
        notifyDataSetChanged()
    }

    companion object {
        val TYPE_NORMAL: Int = 0 // 普通
        val TYPE_HEADER: Int = 1 // 头部 View
        val TYPE_FOOTER: Int = 2 // 底部 View
    }

    /**
     * 头部和底部 ViewHolder
     */
    open class UsedViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}